package com.stylefeng.guns.modular.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.common.constant.Const;
import com.stylefeng.guns.common.persistence.dao.*;
import com.stylefeng.guns.common.persistence.model.TBill;
import com.stylefeng.guns.common.persistence.model.TOrder;
import com.stylefeng.guns.common.persistence.model.TOrderFee;
import com.stylefeng.guns.common.persistence.model.TTrain;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.datascope.DataScope;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.page.PageInfoBT;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.core.util.StringUtils;
import com.stylefeng.guns.modular.system.service.ITOrderFeeService;
import com.stylefeng.guns.modular.system.service.ITOrderService;
import com.stylefeng.guns.modular.system.service.ITTrainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * 车次核销控制器
 *
 * @author fengshuonan
 * @Date 2018-03-07 11:50:54
 */
@Controller
@RequestMapping("/tTrain")
public class TTrainController extends BaseController {

    private String PREFIX = "/system/tTrain/";

    @Autowired
    private ITTrainService tTrainService;

    @Autowired
    private TOrderFeeMapper orderFeeWarpper;


    @Autowired
    private ITOrderFeeService itOrderFeeService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TOrderMapper orderMapper;

    @Autowired
    private ITOrderService tOrderService;

    @Autowired
    TTrainMapper tTrainMapper;


    @Autowired
    TBillMapper billMapper;

    @Autowired
    private DictMapper tDictMapper;
    /**
     * 跳转到车次核销首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "tTrain.html";
    }

    @RequestMapping("/indexDis")
    public String indexDis() {
        return "/system/tOrder/orderDistribution/tTrainDis.html";
    }
    @RequestMapping("/indexHxDis")
    public String indexHxDis() {
        return "/system/tOrder/orderDistribution/tTrainHxDis.html";
    }

    @RequestMapping("/indexHxTransfer")
    public String indexHxTransfer() {
        return "/system/tOrder/transfer/transferHxDis.html";
    }
    /**
     * 跳转到添加车次核销
     */
    @RequestMapping("/tTrain_add")
    public String tTrainAdd() {
        return PREFIX + "tTrain_add.html";
    }

    /**
     * 跳转到修改车次核销
     */
    @RequestMapping("/tTrain_update/{tTrainId}")
    public String tTrainUpdate(@PathVariable Integer tTrainId, Model model) {
        TTrain tTrain = tTrainService.selectById(tTrainId);
        model.addAttribute("item",tTrain);
        LogObjectHolder.me().set(tTrain);
        return PREFIX + "tTrain_edit.html";
    }

    @RequestMapping("/tTrainDis_update/{tTrainId}")
    public String tTrainDisUpdate(@PathVariable Integer tTrainId, Model model) {
        TTrain tTrain = tTrainService.selectById(tTrainId);
        model.addAttribute("item",tTrain);
        LogObjectHolder.me().set(tTrain);
        return  "/system/tOrder/orderDistribution/tTrainDis_edit.html";
    }

    @RequestMapping("/tTrainDis_ref/{tTrainId}")
    public String tTrainDisRef(@PathVariable Integer tTrainId, Model model) {
        TTrain tTrain = tTrainService.selectById(tTrainId);
        model.addAttribute("item",tTrain);
        EntityWrapper<TOrder> wrapper=new EntityWrapper<>();
        wrapper.where("train_no={0}",tTrain.getTrainNo());
        List<TOrder> orders=tOrderService.selectList(wrapper);
        String ids="";
        for(TOrder tOrder:orders){
            ids=ids+tOrder.getId()+",";
        }
        model.addAttribute("ids", ids.substring(0,ids.length()-1));
        LogObjectHolder.me().set(tTrain);
        return  "/system/tOrder/orderDistribution/distributionRef.html";
    }



    @RequestMapping("/tTrainDisHx_update/{tTrainId}")
    public String tTrainDisHxUpdate(@PathVariable Integer tTrainId, Model model) {
        TTrain tTrain = tTrainService.selectById(tTrainId);
        EntityWrapper<TOrder> entityWrapper=new EntityWrapper<>();
        entityWrapper.where("train_id={0}",tTrainId);
        List<TOrder> orders=tOrderService.selectList(entityWrapper);
        List<Map<String,Object>> updateFeeids=tTrainMapper.selectUpFeeid(tTrain.getTrainNo(),"3","0");
        List<Map> bills=billMapper.billMap(updateFeeids.get(0).get("order_id").toString());
        model.addAttribute("bills", bills);
        model.addAttribute("item",tTrain);
        LogObjectHolder.me().set(tTrain);
        return  "/system/tOrder/orderDistribution/tTrainDisHx_edit.html";
    }

    @RequestMapping("/tTrainTransferHxUpdate/{tTrainId}")
    public String tTrainTransferHxUpdate(@PathVariable Integer tTrainId, Model model) {
        TTrain tTrain = tTrainService.selectById(tTrainId);
        List<Map> bills=billMapper.selectXJBills(tTrainId);
        model.addAttribute("bills", bills);
        model.addAttribute("item",tTrain);
        LogObjectHolder.me().set(tTrain);
        return  "/system/tOrder/transfer/transferHx_edit.html";
    }

    @RequestMapping("/orderZTHX")
    @ResponseBody
    public Object orderZTHX(String id){
        EntityWrapper<TOrder> entityWrapper=new EntityWrapper<>();
        entityWrapper.where("train_id={0}",id);
        List<TOrder> orders=tOrderService.selectList(entityWrapper);
        List<Integer> ids=new ArrayList<>();
        for(TOrder order:orders){
            EntityWrapper<TOrderFee> eWrapper = new EntityWrapper<TOrderFee>();
            eWrapper.where("order_id={0}",order.getId()+"");
            List<TOrderFee> orderFees=orderFeeWarpper.selectList(eWrapper);
            for(TOrderFee tOrderFee:orderFees){
                tOrderFee.setAuditStatus(3);
                ids.add(tOrderFee.getId());
                //todo 操作人
//                itOrderFeeService.updateById(tOrderFee);
            }
            order.setFlow_status(4);
            orderMapper.updateById(order);
            orderFeeWarpper.batchOrderFeeAuditStatus("3","",ids);
        }
        TTrain tTrain=new TTrain();
        tTrain.setId(Integer.valueOf(id));
        tTrain.setStatus(1);
        tTrainService.updateById(tTrain);
        return super.SUCCESS_TIP;
    }


    @RequestMapping("/orderBatchZTHX")
    @ResponseBody
    public Object orderBatchZTHX(String mId){

        for(String id:mId.split(",")){
            EntityWrapper<TOrder> entityWrapper=new EntityWrapper<>();
            entityWrapper.where("train_id={0}",id);
            List<TOrder> orders=tOrderService.selectList(entityWrapper);
            List<Integer> ids=new ArrayList<>();
            List<Integer> mids=new ArrayList<>();
            for(TOrder order:orders){
                EntityWrapper<TOrderFee> eWrapper = new EntityWrapper<TOrderFee>();
                eWrapper.where("order_id={0}",order.getId()+"");
                List<TOrderFee> orderFees=orderFeeWarpper.selectList(eWrapper);
                for(TOrderFee tOrderFee:orderFees){
                    tOrderFee.setAuditStatus(3);
                    ids.add(tOrderFee.getId());
                    //todo 操作人
//                itOrderFeeService.updateById(tOrderFee);
                }
                mids.add(order.getId());
                orderFeeWarpper.batchOrderFeeAuditStatus("3","",ids);
            }
            orderMapper.batchOrderAuditStatus("4",mids);
            TTrain tTrain=new TTrain();
            tTrain.setId(Integer.valueOf(id));
            tTrain.setStatus(1);
            tTrainService.updateById(tTrain);
        }

        return super.SUCCESS_TIP;
    }

    @RequestMapping("/transferBatchHX")
    @ResponseBody
    public Object transferBatchHX(String ids){//中转核销
        for(String id:ids.split(",")){

            long mon_bal_fee=orderFeeWarpper.sumOrderFee(id);

            tTrainService.transferHX(id,mon_bal_fee+"");
        }


        return super.SUCCESS_TIP;
    }

    @RequestMapping("/transferHX")
    @ResponseBody
    public Object transferHX(String id,String mon_bal_fee){//中转核销
        tTrainService.transferHX(id,mon_bal_fee);
        return super.SUCCESS_TIP;
    }

    /**
     * 获取车次核销列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Integer limit, Integer offset) {
        String name= getPara("name");//车次号
        String status= getPara("status");//0待核销 1已核销
        if(StringUtils.isEmpty(status)){
            status="0";//默认待核销
        }
        String beginTime= getPara("beginTime");
        String endTime= getPara("endTime");
        String dot_id = ShiroKit.getUser().getDotId()+"";
        Page<Map<String, Object>> page=new Page(offset,limit);
        PageInfoBT pageInfoBT=new PageInfoBT(page);
        List<Map<String, Object>> list = tTrainService.checkTrainList(page,beginTime,endTime,name,status,dot_id);
        pageInfoBT.setData(list);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }

    /**
     * 获取车次核销列表
     */
    @RequestMapping(value = "/disList")
    @ResponseBody
    public Object disList(Integer limit, Integer offset) {
        String name= getPara("name");
        String status= getPara("status");
        if(StringUtils.isEmpty(status)){
            status="2";
        }
        String train_no= getPara("train_no");
        String beginTime= getPara("beginTime");
        String endTime= getPara("endTime");
        Page<Map<String, Object>> page=new Page(offset,limit);
        PageInfoBT pageInfoBT=new PageInfoBT(page);
        Map m=new HashMap();

        List<Map<String, Object>> list = tTrainService.checkTrainDirsList(page,beginTime,endTime,name,status,ShiroKit.getUser().getDotId()+"");

        pageInfoBT.setData(list);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }

    /**
     * 获取车次核销列表
     */
    @RequestMapping(value = "/disHxList")
    @ResponseBody
    public Object disHxList(Integer limit, Integer offset) {
        String name= getPara("name");
        String status= getPara("status");
        if(StringUtils.isEmpty(status)){
            status="3";
        }
        String train_no= getPara("train_no");
        String beginTime= getPara("beginTime");
        String endTime= getPara("endTime");
        String dot_id = userMapper.selectById(ShiroKit.getUser().getId()).getDot_id() + "";

        Page<Map<String, Object>> page=new Page(offset,limit);
        PageInfoBT pageInfoBT=new PageInfoBT(page);
        Map m=new HashMap();

        DataScope dataScope = new DataScope(ShiroKit.getDeptDataScope());
        List<Map<String, Object>> list = tTrainService.checkTrainDirsList(page,beginTime,endTime,name,status,dot_id);

        pageInfoBT.setData(list);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }


    /**
     * 获取车次核销列表
     */
    @RequestMapping(value = "/transferHxList")
    @ResponseBody
    public Object transferHxList(Integer limit, Integer offset) {
        String name= getPara("name");
        String status= getPara("status");
        if(StringUtils.isEmpty(status)){
            status="0";
        }
        String train_no= getPara("train_no");
        String beginTime= getPara("beginTime");
        String endTime= getPara("endTime");
        String dot_id = userMapper.selectById(ShiroKit.getUser().getId()).getDot_id() + "";

        Page<Map<String, Object>> page=new Page(offset,limit);
        PageInfoBT pageInfoBT=new PageInfoBT(page);
        Map m=new HashMap();

        DataScope dataScope = new DataScope(ShiroKit.getDeptDataScope());
        List<Map<String, Object>> list = tTrainService.checkTrainZZList(page,beginTime,endTime,name,status,dot_id);

        pageInfoBT.setData(list);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }

    /**
     * 获取车次核销列表
     */
    @RequestMapping(value = "/transferHxGroup")
    @ResponseBody
    public Object transferHxGroup(Integer limit, Integer offset) {
        String name= getPara("name");
        String status= getPara("status");
        if(StringUtils.isEmpty(status)){
            status="0";
        }
        String train_no= getPara("train_no");
        String beginTime= getPara("beginTime");
        String endTime= getPara("endTime");
        String dot_id = userMapper.selectById(ShiroKit.getUser().getId()).getDot_id() + "";

        Map m=new HashMap();

        DataScope dataScope = new DataScope(ShiroKit.getDeptDataScope());
        Map<String, Object> map = tTrainService.checkTrainZZListGroup(null,beginTime,endTime,name,status,dot_id);

        return map;
    }

    @RequestMapping(value = "/detailList")
    @ResponseBody
    public Object detailList(Integer limit, Integer offset) {
        String batch_no= getPara("batch_no");
        Page<Map<String, Object>> page=new Page(offset,limit);
        PageInfoBT pageInfoBT=new PageInfoBT(page);
        Map m=new HashMap();
        DataScope dataScope = new DataScope(ShiroKit.getDeptDataScope());
        List<Map<String, Object>> list = tTrainService.checkTrainDetailList(batch_no);
        pageInfoBT.setData(list);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }



    @RequestMapping(value = "/detailDisList")
    @ResponseBody
    public Object detailDisList(Integer limit, Integer offset) {
        String batch_no= getPara("batch_no");
        Page<Map<String, Object>> page=new Page(offset,limit);
        PageInfoBT pageInfoBT=new PageInfoBT(page);
        List<Map<String, Object>> list = tTrainService.checkTrainDisDetailList(batch_no);
        pageInfoBT.setData(list);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }



    @RequestMapping(value = "/detailDisPrintList")
    @ResponseBody
    public Object detailDisPrintList(Integer limit, Integer offset) {
        String batch_no= getPara("batch_no");
        Page<Map<String, Object>> page=new Page(0,1000);
        PageInfoBT pageInfoBT=new PageInfoBT(page);
        Map m=new HashMap();
        DataScope dataScope = new DataScope(ShiroKit.getDeptDataScope());
        List<Map<String, Object>> list = tTrainService.checkTrainDisDetailList(batch_no);
        pageInfoBT.setData(list);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }

    @RequestMapping(value = "/detailZZList")
    @ResponseBody
    public Object detailZZList(Integer limit, Integer offset) {
        String batch_no= getPara("batch_no");
        Page<Map<String, Object>> page=new Page(offset,limit);
        PageInfoBT pageInfoBT=new PageInfoBT(page);
        Map m=new HashMap();
        List<Map<String, Object>> list = tTrainService.checkTrainZZDetailList(batch_no);
        pageInfoBT.setData(list);
        pageInfoBT.setCount(page.getTotal());
        return pageInfoBT;
    }
    /**
     * 新增车次核销
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(TTrain tTrain) {
        tTrainService.insert(tTrain);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除车次核销
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer tTrainId) {
        tTrainService.deleteById(tTrainId);
        return SUCCESS_TIP;
    }

    /**
     * 车次核销--功能
     */

    @RequestMapping(value = "/trainHX")
    @ResponseBody
    public Object update(TTrain tTrain) {
        String mA=getPara("mA");
        String mB=getPara("mB");
        String mC=getPara("mC");
        String mD=getPara("mD");
        String mE=getPara("mE");
        String xj=getPara("xj");//现结
        String gz=getPara("gz");//挂账
        tTrain.setStatus(1);
        // 页面传 月结费用 现结费用总额
        //插入balance表 id更新到orderfee balance_id
        //插入 bill表 更新balance_detail  bill_id

        String billNum= "TT"+ShiroKit.getUser().getId()+"_"+DateUtil.getAllTimes();
        String cash=getPara("cash");
        String weixin=getPara("weixin");
        String alipay=getPara("alipay");
        String bank=getPara("bank");
        TBill bill=new TBill();
        bill.setAlipay(Float.valueOf(alipay));
        bill.setWeixin(Float.valueOf(weixin));
        bill.setBank(Float.valueOf(bank));
        bill.setCash(Float.valueOf(cash));
        bill.setDotId(ShiroKit.getUser().getDotId());
        bill.setEditUser(ShiroKit.getUser().getId());
        bill.setCreateTime(new Date());
        bill.setBillNum(billNum);
        tTrainService.checkTrain(tTrain,bill,mA,mB,mC,mD,mE,xj,gz);
        return super.SUCCESS_TIP;
    }

    /**
     * 修改车次核销
     */
    @RequestMapping(value = "/transferUpdate")
    @ResponseBody
    @Transactional
    public Object transferUpdate(String ids,String car_no,String driver_name,String phone,String cf,String temOrderFeeS) {
        String mA=getPara("mA");
        String mB=getPara("mB");
        String mC=getPara("mC");
        String mD=getPara("mD");
        String mE=getPara("mE");
        String mF=getPara("mF");
        String cash=getPara("cash");
        String weixin=getPara("weixin");
        String alipay=getPara("alipay");
        String bank=getPara("bank");
        String xj=getPara("xj");//下家现结费用
        String gz=getPara("gz");//下家月结费用
        String transfer_name=getPara("transfer_name");//下游网点
        String driverId=getPara("driverId");//下游网点
        String transferId=getPara("transferId");//下游网点

        String billNum= "TT"+ShiroKit.getUser().getId()+"_"+DateUtil.getAllTimes();

        TBill bill=new TBill();
        bill.setAlipay(Float.valueOf(alipay));
        bill.setWeixin(Float.valueOf(weixin));
        bill.setBank(Float.valueOf(bank));
        bill.setCash(Float.valueOf(cash));
        bill.setDotId(ShiroKit.getUser().getDotId());
        bill.setEditUser(ShiroKit.getUser().getId());
        bill.setCreateTime(new Date());
        bill.setBillNum(billNum);

//        String bath_no = ShiroKit.getUser().getId() + DateUtil.getAllTimes();
        Map param=new HashMap();
        param.put("dot_id",ShiroKit.getUser().getDotId());
        param.put("nType", Const.NTYPE_02); // 类别 00 初始 01 配送 02 中转 03 自提  04 月结
        String bath_no = tDictMapper.getNumCode(param);
        JSONArray jsonArray = JSONArray.parseArray(temOrderFeeS);
        List<Map> maps = jsonArray.toJavaList(Map.class);
        TTrain tTrain=new TTrain();
        tTrain.setCarNo(car_no);
        tTrain.setDriver_id(driverId);
        tTrain.setDot_id(ShiroKit.getUser().getDotId());
        tTrain.setDriverName(driver_name);
        tTrain.setPhone(phone);
        tTrain.setSendDeptName(transfer_name);
        tTrain.setTrainNo(bath_no);
        tTrain.setSendDeptId(transferId);
        tTrain.setTrain_type("3");//0 初始 1 自提 2配送 3中转
        tTrain.setUserId(ShiroKit.getUser().getId());
        tTrain.setCreateTime(new Date());
        tTrain.setReportDate(new Date());
        tOrderService.addAndTRTrian(bill,ids,tTrain,cf,maps,mA,mB,mC,mD,mE,mF,xj,transfer_name,gz);
        SUCCESS_TIP.setCode(tTrain.getId());

        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/updateDis")
    @ResponseBody
    @Transactional
    public Object updateDis(TTrain tTrain) {
        String ys=getPara("ys");
        if(ys!=null&&"0".equals(ys)){
            //无费用产生，无需核销
            tTrain.setStatus(4);
        }else{
            tTrain.setStatus(3);
        }

        String billNum= "TT"+ShiroKit.getUser().getId()+"_"+DateUtil.getAllTimes();
        String cash=getPara("cash");
        String weixin=getPara("weixin");
        String alipay=getPara("alipay");
        String bank=getPara("bank");
        TBill bill=new TBill();
        bill.setAlipay(Float.valueOf(alipay));
        bill.setWeixin(Float.valueOf(weixin));
        bill.setBank(Float.valueOf(bank));
        bill.setCash(Float.valueOf(cash));
        bill.setDotId(ShiroKit.getUser().getDotId());
        bill.setEditUser(ShiroKit.getUser().getId());
        bill.setCreateTime(new Date());
        bill.setBillNum(billNum);
        tTrainService.checkTrainDis(tTrain,bill,ys);
        return super.SUCCESS_TIP;
    }
    /**
     * 车次核销详情
     */
    @RequestMapping(value = "/detail/{tTrainId}")
    @ResponseBody
    public Object detail(@PathVariable("tTrainId") Integer tTrainId) {
        return tTrainService.selectById(tTrainId);
    }
}
